<?php

namespace App\Service\OpenShop\SiteLocation;

use App\Http\Middleware\OpenShop\UserPermissionAuth;
use App\Library\Rms\RmsUserApi;
use App\Models\BaseModel;
use App\Models\Common\ConfigModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageUserModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Service\OpenShop\Feishu\OrganizationManageService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class PermissionService
{
    public const URI_HOUSE_LISTS = 'openshop.sitelocation.siteform.houseresourceslist';

    const ROLE_TOTAL            = 1; // 全部权限
    const ROLE_PROVINCE_DEVELOP = 2; // 省区开发
    const ROLE_OTHER            = 3; // 其他权限
    const ROLE_ZS               = 4; // 招商中心

    const LIST_TYPE_MISSION = 1; // 待办任务列表
    const LIST_TYPE_HOUSE   = 2; // 房源列表

    /**
     * 权限通用返回值
     * @param bool $isAll
     * @param string $rawSql
     * @return array
     */
    private function permissionData(bool $isAll, string $rawSql = '', int $role = 0): array
    {
        if ($isAll) {
            $role = self::ROLE_TOTAL;
        }

        return [
            'isAll'  => $isAll,
            'rawSql' => $rawSql,
            'role'   => $role,
        ];
    }

    /**
     * 房源列表权限
     * @param int $userId
     * @return array
     */
    public function orderLists(int $userId, int $listType = self::LIST_TYPE_MISSION): array
    {
        $uri            = self::URI_HOUSE_LISTS;
        $permissionList = getRmsUserPermissionList([], UserPermissionAuth::MODULE_OPEN_SHOP);

        // 判断是否拥有所有权限
        if (in_array($uri . '_all', $permissionList)) {
            return $this->permissionData(true);
        }

        // 选址管理员
        // 总部负责人 - 看全部   核查专员
        $configs = ConfigModel::query()
                              ->whereIn('name', [ConfigModel::SITE_MANAGER, ConfigModel::SITE_SUPER_ADMIN, ConfigModel::VERIFY_PERSONNEL])
                              ->select('name', 'value')
                              ->get();

        foreach ($configs as $config) {
            $valueArr = json_decode($config['value'], true);
            if (in_array($userId, $valueArr)) {
                return $this->permissionData(true);
            }
        }

        // 省总 - 看全部
        $areaList = OrganizationManageService::getAreaListByUserId($userId);
        if ($areaList['isAll'] || $areaList['list']) {
            return $this->permissionData(true);
        }

        // 省区实习总
        $userOrganization = OpenShopOrganizationManageModel::query()
            ->whereRaw(DB::raw("JSON_CONTAINS(operationAttacheUser, JSON_OBJECT('uid', {$userId}))"))
            ->count();
        if ($userOrganization) {
            return $this->permissionData(true);
        }

        // 省区开发 - 看省区&&自己
        $manageUser = OpenShopOrganizationManageUserModel::query()
            ->where('userId', $userId)
            ->where('type', OpenShopOrganizationManageUserModel::TYPE_PROVINCE_DEVELOP)
            ->with(['manageRel.regionRel'])
            ->get();
        if ($manageUser->count()) {
            $provinces = [];
            $manageUser->map(function ($manageUser) use (&$provinces){
                try {
                    $addProvinceCodes = $manageUser->manageRel->regionRel->pluck('provinceCode')->toArray();
                } catch (\Exception $exception) {
                    $addProvinceCodes = [];
                }
                $provinces = array_merge($provinces, $addProvinceCodes);
            });

            $builder = OpenShopSiteLocationModel::query()
                                                ->where(function ($query) use ($userId, $provinces) {
                                                    $query->whereIn('provinceCode', $provinces)
                                                          ->orWhere('createdByUid', $userId)
                                                          ->orWhere('developConsultantId', $userId);
                                                })
                                                ->select('orderNo');

            return $this->permissionData(false, "orderNo in (" . BaseModel::toSqlWithParam($builder) . ')',
                self::ROLE_PROVINCE_DEVELOP);
        }

        // 招商中心
        if ($this->checkZs($userId)) {

            // 房源列表看全部的
            if ($listType == self::LIST_TYPE_HOUSE) {
                return $this->permissionData(true, '', self::ROLE_ZS);
            }

            // 任务只能看自己的,↓
        }

        // 其他看自己
        $builder = OpenShopSiteLocationModel::query()
            ->where(function ($query) use ($userId) {
                $query->where('createdByUid', $userId)
                    ->orWhere('developConsultantId', $userId);
            })
            ->select('orderNo');

        return $this->permissionData(false, "orderNo in (" . BaseModel::toSqlWithParam($builder) . ')',
            self::ROLE_OTHER);
    }

    /**
     * 检查是否为招商中心的员工
     * @param int $userId
     * @return bool
     */
    private function checkZs(int $userId): bool
    {
        $userIds = Cache::remember('checkZs', 3600, function () {
            return collect((new RmsUserApi())->getFsUsers('', ['rmsUserId'], 'od-9b3d254f7b63605400a1f74c50586d3c')['data']['lists'])->pluck('rmsUserId')->toArray();
        });

        return in_array($userId, $userIds);
    }
}
